<?php

namespace Beerus\Modules\GoodsTest\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\GoodsTestActivity\FineGoodsJoinModel;
use Biz\model\GoodsTestActivity\FineGoodsJoinRecordModel;
use Biz\model\GoodsTestActivity\FineGoodsModel;
use Biz\model\GoodsTestActivity\FineGoodsPeopleReplaceModel;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\module\Packages\Logistics\TrackingMore;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Biz\service\GoodsTestActivity\PushNoticeService;
use Biz\service\NewProduct\NewProductWinnerListService;
use Doraemon\service\User;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\Phone as PhoneModel;
use hhz\constant\basic\UserExtendPhoneScene;

class DetailJoinSelectedController extends Controller
{
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content, $id)
    {
        $joined = FineGoodsService::getJoined($id);
        $countJoined = count($joined);
        $activityInfo = FineGoodsModel::first(['id'=>$id]);
        $list = [];
        if ($countJoined == $activityInfo['goods_num'] && $countJoined > 0) {
        $list = FineGoodsService::formatJoined($joined);
        }
        Admin::script($this->toShipScript());
        Admin::script($this->toReplaceScript());
        $description = FineGoodsService::peopleReplaceNewInfo($id);
        $gridModel = new GridDataModel($list);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $description ,$activityInfo) {
                //测评类型的活动 不需要展示替换操作
                if($activityInfo['type'] < FineGoodsModel::TYPE_EVALUATION) {
                    $grid->header(function () use ($description) {
                        $html = "<div style='font-size: 20px'>";
                        $html .= '<sapn style="font-weight: bold ; color: red">替换用户操作记录：「'.$description['header'].'」</sapn>&emsp;';
                        $html .= "</div>";

                        return $html;
                    });
                }
                //显示当前页的序号
                $grid->number('序号');
                $grid->rows(function ($row, $number) {
                    $row->column('number', $number + 1);
                });

                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->disableCreateButton();
                $grid->column('user_avatar', '用户头像')->image(100, 100);
                $grid->column('id', 'ID');
                $grid->column('user_nick', '用户昵称');
                $grid->column('user_uid', '用户uid')->copyable();
                $grid->column('fans_num', '用户粉丝数');
                $grid->column('tag_list', '用户标签');
                $grid->column('logistics_status', '发货状态')->using(FineGoodsJoinModel::LOGISTICS_STATUS_MAP);
                $grid->column('couriers_info_courier_name', '快递公司');
                $grid->column('tracking_number', '物流单号')->copyable();
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($activityInfo) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    if ($actions->row->logistics_status == FineGoodsJoinModel::LOGISTICS_STATUS_NO_SHIPPED) {
                        $actions->prepend('<a class="fa fa-edit to-ship" data-id="'.$actions->row->record_id.'"  href="javascript:void(0);")>填写快递信息</a>');
                        //测评类型的活动 不需要展示替换操作
                        if($activityInfo['type'] < FineGoodsModel::TYPE_EVALUATION) {
                            $actions->prepend('<a class="fa fa-edit to-replace" data-id="'.$actions->row->id.'"  href="javascript:void(0);")>替换用户</a>');
                        }
                    }
                });
            }
        );
        $tab = new Tab();
        $tab->addLink("活动详情页 ", url("/admin/goodsTest/detail/$id"), false);
        $tab->add('获选名单', $grid->render(), true);
        $tab->addLink('测评报告管理', url("/admin/goodsTest/reportList/index/$id"), false);
        $tab->addLink('测评报告', url("/admin/goodsTest/detail/report/$id"), false);
        $content->row($tab);

        return $content
            ->header('获选名单')
            ->breadcrumb(['text' => '审核列表', 'url' => '/goodsTest/index'], ['text' => '获选名单']);
    }

    private function toShipScript(): string
    {
        return <<<SCRIPT
        $('.to-ship').unbind('click').click(function(){
            var id=$(this).data('id');
            layer.open({
                type: 2,
                title: '',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['600px', '600px'],
                content: '/admin/goodsTest/joinSelected/index/'+id+'/editShip',
            });
        });
SCRIPT;
    }

    private function toReplaceScript(): string
    {
        return <<<SCRIPT
        $('.to-replace').unbind('click').click(function(){
            var id=$(this).data('id');
            layer.open({
                type: 2,
                title: '',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['600px', '600px'],
                content: '/admin/goodsTest/joinSelected/index/'+id+'/toReplace',
            });
        });
SCRIPT;
    }

    /**
     * 填写物流单号
     * @param \Illuminate\Http\Request $request
     * @param \App\Admin\Extensions\WorkContent $content
     * @param $id
     * @return \App\Admin\Extensions\WorkContent
     */
    public function editShip(Request $request, WorkContent $content, $id): WorkContent
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $where = [
            'id' => $id,
        ];
        $field = ['id', 'uid', 'name', 'encrypt_phone_id', 'address', 'fine_goods_id'];
        $info = FineGoodsJoinRecordModel::get($field, $where);
        $info['phone'] = PhoneModel::getExtendPhone($info['encrypt_phone_id'], UserExtendPhoneScene::GOODS_TEST_JOIN_PHONE);
        $userInfo = User::getUser($info['uid']);
        $info['nick'] = $userInfo['nick'];
        $info['basic_title'] = FineGoodsModel::first(['id' => $info['fine_goods_id']], 'basic_title') ?? '';
        $info['id'] = FineGoodsJoinModel::get('id', ['record_id' => $id]);//获选人主键id （fine_goods_test_activity_join）
        $form = new Form($info);
        $form->hidden('id');
        $form->hidden('uid');
        $form->hidden('basic_title');
        $form->hidden('fine_goods_id');
        $couriers = NewProductWinnerListService::getCourierList();
        $couriers = NewProductWinnerListService::handleData($couriers ?? [], 'courier_id',
            'courier_name');
        $form->text('nick', '用户昵称')->disable();
        $form->text('name', '收货人')->disable();
        $form->text('phone', '收货人联系电话')->disable();
        $form->text('address', '收货人地址')->disable();
        $form->select('courier', '物流公司')->options($couriers)->required();
        $form->text('tracking_number', '物流单号');
        $form->confirm('确认提交吗？', 'edit');
        $form->action('/admin/goodsTest/joinSelected/saveShip');

        return $content
            ->body($form);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     */
    public function saveShip(Request $request)
    {
        $id = $request->input('id', 0);//获选人主键id
        $courierId = $request->input('courier', 0);//物流公司id
        $trackingNumber = $request->input('tracking_number', '');//物流单号
        $basic_title = $request->input('basic_title', '');//好物名称
        $uid = $request->input('uid', 0);//uid
        $fine_goods_id = $request->input('fine_goods_id', 0);//fine_goods_id

        if (!$id || !$courierId || !$trackingNumber || !$basic_title || !$fine_goods_id || !$uid) {
            $error = new MessageBag(['title' => '参数错误']);

            return redirect("/admin/goodsTest/joinSelected/index/$id/editShip")->with(compact('error'));
        }
        $courierInfo = mShopCourier::getCourier('*', ['courier_id' => $courierId]);
        if ($courierInfo) {
            $carrierCode = $courierInfo['trackingmore_code'];
            //创建物流信息
            $data = TrackingMore::createTracking($carrierCode, $trackingNumber,
                ['logistics_channel' => TrackingMore::LOGISTICS_CHANNEL_GOODS_TEST_ACTIVITY]);
            //更新获选名单数据
            if ($data['meta']['code'] == 200) {
                try {
                    PushNoticeService::afterSendGoods($courierId,
                        $trackingNumber,
                        $id,
                        $basic_title,
                        $courierInfo['courier_name'], $uid);
                } catch (Exception $e) {
                    $error = new MessageBag(['title' => $e->getMessage()]);

                    return redirect("/admin/goodsTest/joinSelected/index/$id/editShip")->with(compact('error'));

                }
            } else {

                $error = new MessageBag(['title' => $data['meta']['message']]);

                return redirect("/admin/goodsTest/joinSelected/index/$id/editShip")->with(compact('error'));
            }
        }
        $success = new MessageBag(['title' => '操作成功']);

        return redirect("/admin/goodsTest/joinSelected/index/$fine_goods_id/editShip?code=1")->with(compact('success'));
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param \App\Admin\Extensions\WorkContent $content
     * @param $id
     * @return \App\Admin\Extensions\WorkContent
     */
    public function toReplace(Request $request, WorkContent $content, $id): WorkContent
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        try {
            $info = FineGoodsService::peopleReplaceDetail($id);
        } catch (Exception $e) {
            $info = [];
            Log::error('error', $e->getMessage());
        }
        $info['from_id'] = $info['prefer']['from_id'] ?? 0;
        $info['from_uid'] = $info['prefer']['from_uid'] ?? 0;

        $info['to_id'] = $info['not_prefer']['to_id'] ?? 0;
        $info['to_uid'] = $info['not_prefer']['to_uid'] ?? 0;
        $form = new Form($info);
        $form->hidden('id');
        $form->hidden('from_id');
        $form->hidden('from_uid');
        $form->hidden('to_id');
        $form->hidden('to_uid');

        $preferHtml = '<ul class="list-unstyled">';
        $preferHtml .= '<li>粉丝数:'.$info['prefer']['fans_num'].'</li>';
        $preferHtml .= '<li>昵称:'.$info['prefer']['user_nick'].'</li>';
        $preferHtml .= '<li>内容领域标签:'.$info['prefer']['tag_list'].'</li>';
        $preferHtml .= '<li>头像:<img  width="100px;" src="'.$info['prefer']['user_avatar'].'"  alt="头像" /> '.'</li>';
        $preferHtml .= '</ul>';

        $form->divider('首选人信息');
        $form->html($preferHtml, '首选人信息');

        if ($info['to_id'] > 0 && $info['to_uid'] > 0) {

            $notPreferHtml = '<ul class="list-unstyled">';
            $notPreferHtml .= '<li>粉丝数:'.$info['not_prefer']['fans_num'].'</li>';
            $notPreferHtml .= '<li>昵称:'.$info['not_prefer']['user_nick'].'</li>';
            $notPreferHtml .= '<li>内容领域标签:'.$info['not_prefer']['tag_list'].'</li>';
            $notPreferHtml .= '<li>头像:<img  width="100px;" src="'.$info['not_prefer']['user_avatar'].'"  alt="头像" /> '.'</li>';
            $notPreferHtml .= '</ul>';
        }else{
            $notPreferHtml = '<ul class="list-unstyled">';
            $notPreferHtml .= '<span style="color: red;font-size: medium">暂无备选人</span>';
            $notPreferHtml .= '</ul>';
            $form->disableSubmit();
        }
        $form->divider('备选人信息');
        $form->html($notPreferHtml, '备选人信息');
        $form->confirm('确认提交吗？', 'edit');
        $form->action('/admin/goodsTest/joinSelected/saveReplace');

        return $content
            ->body($form);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     */
    public function saveReplace(Request $request)
    {
        $id = $request->input('id', 0);//活动id
        $fromId = $request->input('from_id', 0);//首选人id
        $fromUid = $request->input('from_uid', '');//首选人uid
        $toId = $request->input('to_id', '');//备选人 id
        $toUid = $request->input('to_uid', 0);//备选人 uid
        if (!$id || !$fromId || !$fromUid || !$toId || !$toUid) {
            $error = new MessageBag(['title' => '参数错误']);

            return redirect("/admin/goodsTest/joinSelected/index/$id/toReplace?code=1")->with(compact('error'));
        }
        $operate_type = FineGoodsPeopleReplaceModel::OPERATE_TYPE_ADMIN;
        $operate_id = Admin::user()->id;
        try {
            FineGoodsService::peopleReplace($id, $fromId, $fromUid, $toId, $toUid, $operate_type,
                $operate_id);
        } catch (Exception $e) {
            $error = new MessageBag(['title' => $e->getMessage()]);
            Log::error('error', $e->getMessage());

            return redirect("/admin/goodsTest/joinSelected/index/$id/toReplace")->with(compact('error'));
        }
        $success = new MessageBag(['title' => '操作成功']);

        return redirect("/admin/goodsTest/joinSelected/index/$id/toReplace?code=1")->with(compact('success'));
    }
}
